package com.yxw.live_vod_boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_boot.dto.ClientSendTalkDTO;
import com.yxw.live_vod_boot.dto.CreateSessionTalkDto;
import com.yxw.live_vod_boot.dto.PageSessionTalkDto;
import com.yxw.live_vod_boot.dto.PageTalkRecodesDto;
import com.yxw.live_vod_boot.entity.*;
import com.yxw.live_vod_boot.enums.MqttTopicEnum;
import com.yxw.live_vod_boot.mapper.*;
import com.yxw.live_vod_boot.mqtt.MqttGateway;
import com.yxw.live_vod_boot.service.SessionTalkService;
import com.yxw.live_vod_boot.utils.HuaWeiObsUtil;
import com.yxw.live_vod_boot.utils.JsonUtils;
import com.yxw.live_vod_boot.utils.PageUtils;
import com.yxw.live_vod_boot.utils.UserUtil;
import com.yxw.live_vod_boot.vo.MqttNoticeVo;
import com.yxw.live_vod_boot.vo.PageSessionTalkVo;
import com.yxw.live_vod_boot.vo.PageTalkRecodesVo;
import com.yxw.live_vod_boot.vo.TalkSeesionInfoVo;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.CommonErrorEnum;
import com.yxw.yxnet_cd_center.common.enums.FileClassifyEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author liuxin
 * 2023.12.04
 * 会话管理
 */
@Slf4j
@Service
public class SessionTalkServiceImpl extends ServiceImpl<SessionTalkMapper, YxSessionTalkEntity> implements SessionTalkService {

    @Value("${file.video.max.size}")
    private long fileVideoMaxSize;

    /**
     * 图片文件最大大小
     */
    @Value("${file.image.max.size}")
    private long fileImageMaxSize;


    @Autowired
    private MqttGateway mqttGateway;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private SessionTalkRecordMapper sessionTalkRecordMapper;

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private HuaWeiObsUtil huaWeiObsUtil;

    @Autowired
    private ShopMapper shopMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendTalkByShare(YxSysShareEntity shareEntity) {
        //校验发送消息数
//        this.validataFollow(sessionId,shareEntity.getShareUserId(),shareEntity.getShareUserType(),shareEntity.getUserId(),1);
        //查询发送者和被发送者之间有没有会话历史消息
        //没有回话就先创建会话
        String sessionId="";
        LambdaQueryWrapper<YxSessionTalkEntity> senderWrapper=new LambdaQueryWrapper();
        senderWrapper.eq(YxSessionTalkEntity::getSenderId,shareEntity.getUserId());
        senderWrapper.eq(YxSessionTalkEntity::getReceiverId,shareEntity.getShareUserId());
        YxSessionTalkEntity senderEntity = baseMapper.selectOne(senderWrapper);
        if(null!=senderEntity){
            sessionId=senderEntity.getSessionId();
        }else{
            if(null==senderEntity){
                sessionId= StringUtils.isBlank(sessionId)?UUID.randomUUID().toString().replaceAll("-", ""):sessionId;
                //发送会话记录
                senderEntity = new YxSessionTalkEntity();
                senderEntity.setSessionId(sessionId);
                senderEntity.setSenderId(shareEntity.getUserId());
                senderEntity.setSenderName(shareEntity.getUserName());
                senderEntity.setCreateTime(new Date());
                senderEntity.setUpdateTime(new Date());
                senderEntity.setStatus(1);
                senderEntity.setReceiverId(shareEntity.getShareUserId());
                senderEntity.setReceiverName(shareEntity.getShareUserName());
                senderEntity.setSenderType(1);
                senderEntity.setReceiverType(shareEntity.getShareUserType());
                if(1==shareEntity.getShareUserType()){
                    //查询接收着头像
                    YxSysUserEntity receiverUserEntity = userMapper.selectById(shareEntity.getShareUserId());
                    if(null==receiverUserEntity){
                        throw new BaseException("未查询到接收人员信息");
                    }
                    senderEntity.setHeadUrl(receiverUserEntity.getHeadUrl());
                }else{
                    YxLiveShopEntity yxLiveShopEntity = shopMapper.selectById(shareEntity.getShareUserId());
                    if(null==yxLiveShopEntity){
                        throw new BaseException("未查询到接收店铺信息");
                    }
                    senderEntity.setHeadUrl(yxLiveShopEntity.getShopAvatar());
                }
                baseMapper.insert(senderEntity);
            }
        }
        //接收者与分享者是否存在会话
        LambdaQueryWrapper<YxSessionTalkEntity> receiverWrapper=new LambdaQueryWrapper();
        receiverWrapper.eq(YxSessionTalkEntity::getSenderId,shareEntity.getShareUserId());
        receiverWrapper.eq(YxSessionTalkEntity::getReceiverId,shareEntity.getUserId());
        YxSessionTalkEntity receiverEntity = baseMapper.selectOne(receiverWrapper);
        if(null!=receiverEntity){
            sessionId=receiverEntity.getSessionId();
        }else{
            //接收会话
            receiverEntity = new YxSessionTalkEntity();
            receiverEntity.setSessionId(sessionId);
            receiverEntity.setSenderId(Long.valueOf(shareEntity.getShareUserId()));
            receiverEntity.setSenderName(shareEntity.getShareUserName());
            receiverEntity.setCreateTime(new Date());
            receiverEntity.setUpdateTime(new Date());
            receiverEntity.setStatus(1);
            receiverEntity.setReceiverId(shareEntity.getUserId());
            receiverEntity.setReceiverName(shareEntity.getUserName());
            receiverEntity.setReceiverType(shareEntity.getShareUserType());
            receiverEntity.setSenderType(1);
            //查询接收头像
            YxSysUserEntity senderUserEntity = userMapper.selectById(shareEntity.getUserId());
            if(null==senderUserEntity){
                throw new BaseException("未查询到接收人员信息");
            }
            senderEntity.setHeadUrl(senderUserEntity.getHeadUrl());
            baseMapper.insert(receiverEntity);
        }
        //修改会话时间
        //修改会话状态和时间
        LambdaUpdateWrapper<YxSessionTalkEntity> updateWrapper=new LambdaUpdateWrapper();
        updateWrapper.set(YxSessionTalkEntity::getUpdateTime,new Date());
        updateWrapper.set(YxSessionTalkEntity::getStatus,1);
        updateWrapper.eq(YxSessionTalkEntity::getSessionId,sessionId);
        baseMapper.update(null,updateWrapper);
        //写会话记录
        YxSessionTalkRecordEntity recordEntity = new YxSessionTalkRecordEntity();
        recordEntity.setSessionId(sessionId);
        recordEntity.setSenderId(shareEntity.getUserId());
        recordEntity.setSenderName(shareEntity.getUserName());
        recordEntity.setTalkInfo(shareEntity.getShareContent());
        recordEntity.setCreateTime(new Date());
        recordEntity.setTalkInfoType(2);
        sessionTalkRecordMapper.insert(recordEntity);
        //发送会话消息
        MqttNoticeVo mqttVo = new MqttNoticeVo();
        mqttVo.setType(4);
        //接收人ID
        mqttVo.setReceiverId(shareEntity.getShareUserId());
        mqttVo.setSysTime(new Date());
        //内容
        mqttVo.setContent(shareEntity.getShareContent());
        log.info("推送会话ID=============================================>{}",sessionId);
        log.info("推送会话内容=============================================>{}",shareEntity.getShareContent());
        mqttGateway.sendToMqtt(MqttTopicEnum.TALK_SESSION_TOPIC.getTopic()+shareEntity.getShareUserId(),JsonUtils.toJson(mqttVo));
    }

    /**
     * 查询会话记录
     * @param dto
     * @return
     */
    @Override
    public PageVO<PageTalkRecodesVo> pageTalkRecordes(PageTalkRecodesDto dto) {
        List<PageTalkRecodesVo> voList=new ArrayList<>();
        Page<YxSessionTalkRecordEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxSessionTalkRecordEntity> queryWrapper=new LambdaQueryWrapper();
        List<Integer> statusList=new ArrayList<>();
        statusList.add(0);
        statusList.add(1);
        queryWrapper.in(YxSessionTalkRecordEntity::getOperationState,statusList);
        queryWrapper.and(wq->{
            wq.isNull(YxSessionTalkRecordEntity::getDeleteUserId);
            wq.or().notLike(YxSessionTalkRecordEntity::getDeleteUserId,","+userUtil.getLoginUserId()+",");
        });
        queryWrapper.eq(YxSessionTalkRecordEntity::getSessionId,dto.getSessionId());
        queryWrapper.orderByDesc(YxSessionTalkRecordEntity::getCreateTime);
        Page<YxSessionTalkRecordEntity> entityPage = sessionTalkRecordMapper.selectPage(page, queryWrapper);
        if(null!=entityPage.getRecords() && !entityPage.getRecords().isEmpty()){
            voList= BeanUtil.copyToList(entityPage.getRecords() ,PageTalkRecodesVo.class);
        }
        return PageUtils.get(page,voList);
    }

    /**
     * 删除会话（用于单方面删除会话）
     * @param recordId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTalkRecordeBYId(Long recordId) {
        YxSessionTalkRecordEntity recordEntity = sessionTalkRecordMapper.selectById(recordId);
        if(null==recordEntity){
            throw new BaseException("未查询到需要删除的聊天记录");
        }
        String deleteUserId = recordEntity.getDeleteUserId();
        if(StringUtils.isBlank(deleteUserId) || !deleteUserId.contains(","+userUtil.getLoginUserId()+",")){
           if(StringUtils.isNotBlank(deleteUserId)){
               recordEntity.setDeleteUserId(recordEntity.getDeleteUserId()+userUtil.getLoginUserId()+",");
           }else{
               recordEntity.setDeleteUserId(","+userUtil.getLoginUserId()+",");
           }
            sessionTalkRecordMapper.updateById(recordEntity);
        }
    }

    /**
     * 分页查询会话列表
     * @return
     */
    @Override
    public PageVO<PageSessionTalkVo> pageSessionTalkList(PageSessionTalkDto dto) {
        if(null==dto.getShopId() && null==dto.getUserId()){
            throw new BaseException("查询会话对ID不能为空");
        }
        List<PageSessionTalkVo> voList=new ArrayList<>();
        Page<YxSessionTalkEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxSessionTalkEntity> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(YxSessionTalkEntity::getSenderId,null==dto.getShopId()?dto.getUserId():dto.getShopId());
        queryWrapper.eq(YxSessionTalkEntity::getStatus,1);
        queryWrapper.orderByDesc(YxSessionTalkEntity::getUpdateTime);
        Page<YxSessionTalkEntity> entityPage = baseMapper.selectPage(page, queryWrapper);
        List<YxSessionTalkEntity> records = entityPage.getRecords();
        if(null!=records && !records.isEmpty()){
            for (YxSessionTalkEntity talkEntity:records) {
                PageSessionTalkVo pageSessionTalkVo = new PageSessionTalkVo();
                BeanUtils.copyProperties(talkEntity, pageSessionTalkVo);
                //查询未读消息数
                LambdaQueryWrapper<YxSessionTalkRecordEntity> recordWapper=new LambdaQueryWrapper();
                recordWapper.eq(YxSessionTalkRecordEntity::getSessionId,talkEntity.getSessionId());
                recordWapper.eq(YxSessionTalkRecordEntity::getSenderId,talkEntity.getSenderId());
                recordWapper.eq(YxSessionTalkRecordEntity::getOperationState,0);
                Integer unreadCnt = sessionTalkRecordMapper.selectCount(recordWapper);
                pageSessionTalkVo.setUnreadCnt(unreadCnt);
                voList.add(pageSessionTalkVo);
                //查询会话记录
                PageTalkRecodesDto talkDto=new PageTalkRecodesDto();
                talkDto.setSessionId(talkEntity.getSessionId());
                PageVO<PageTalkRecodesVo> pageTalkRecodesVoPageVO = pageTalkRecordes(talkDto);
                pageSessionTalkVo.setTalkRecodList(pageTalkRecodesVoPageVO.getList());
            }
        }
        return PageUtils.get(page,voList);
    }

    /**
     * 删除会话
     * @param talkId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSessionTalkById(String talkId) {
        //删除该条会话记录下面所有的聊天记录(这里过滤和删除统一用用户ID)
        sessionTalkRecordMapper.deleteRecordByTaskId(talkId,userUtil.getLoginUserId());
        //删除会话
        int cnt = baseMapper.deleteById(talkId);
        if(0==cnt){
            throw  new BaseException("删除失败,请检查会话ID是否正确");
        }
    }

    /**
     * 消息撤回
     * @param recordId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recallMessage(Long recordId) {
        Long userId = userUtil.getLoginUserId();
        YxSessionTalkRecordEntity recordEntity = sessionTalkRecordMapper.selectById(recordId);
        if(null==recordEntity){
            throw new BaseException("撤回消息不存在");
        }
        //消息超过两分钟以后不能撤回，不是自己的消息不能撤回
       if(recordEntity.getSenderId().compareTo(userId)!=0){
           throw new BaseException("只能撤回自己所发送的消息");
       }
        Long startTime = recordEntity.getCreateTime().getTime();
        Long nowTime=System.currentTimeMillis();
        if(nowTime-startTime>12000){
            throw new BaseException("发送消息已超过两分钟,不能撤回");
        }
        recordEntity.setOperationState(0);
        recordEntity.setUpdateTime(new Date());
        sessionTalkRecordMapper.updateById(recordEntity);
    }

    /**
     * 发送会话
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendTalk(ClientSendTalkDTO dto, MultipartFile file) {
        //接收者信息
        Integer receiverType = dto.getReceiverType();
        Integer senderType = dto.getSenderType();
        if((1!=receiverType && 2!=receiverType) || (1!=senderType && 2!=senderType) ){
            throw  new BaseException("发送者/接收者类型有误");
        }
        //校验消息数
//        this.validataFollow(dto.getSessionId(),dto.getReceiverId(),dto.getReceiverType());
        //生成随机会话记录ID
        String talkId = UUID.randomUUID().toString().replaceAll("-", "");
        //组装消息对话-视频和图片声音需要上传
        TalkSeesionInfoVo vo=new TalkSeesionInfoVo();
        if(2==dto.getContentType() || 3==dto.getContentType() || 4==dto.getContentType()){
            vo=uploadFile(dto,file,talkId);
        }else{
            vo.setTalkType(1);
            vo.setContent(dto.getContent());
        }
        //接收人信息(会话记录是反正滴)
        Long receiverId = dto.getSenderId();
        String receiverName="";
        String receiverUrl="";
        if(1==senderType){
            //接收人
            YxSysUserEntity receiverUserEntity = userMapper.selectById(receiverId);
            if(null==receiverUserEntity){
                throw new BaseException("未查询到接收人员信息");
            }
            receiverName=receiverUserEntity.getNickName();
            receiverUrl=receiverUserEntity.getHeadUrl();
        }else{
            YxLiveShopEntity yxLiveShopEntity = shopMapper.selectById(receiverId);
            if(null==yxLiveShopEntity){
                throw new BaseException("未查询到接收店铺信息");
            }
            receiverName=yxLiveShopEntity.getShopName();
            receiverUrl=yxLiveShopEntity.getShopAvatar();
        }
        //发送者信息
        Long senderId = dto.getReceiverId();
        String senderName="";
        if(1==receiverType){
            //接收人
            YxSysUserEntity senderUserEntity = userMapper.selectById(receiverId);
            if(null==senderUserEntity){
                throw new BaseException("未查询到接收人员信息");
            }
            senderName=senderUserEntity.getNickName();
        }else{
            YxLiveShopEntity yxLiveShopEntity = shopMapper.selectById(receiverId);
            if(null==yxLiveShopEntity){
                throw new BaseException("未查询到接收店铺信息");
            }
            senderName=yxLiveShopEntity.getShopName();
        }
        //查询接收人与创建人之间是否存在会话，没有就创建
        LambdaQueryWrapper<YxSessionTalkEntity> receiverWrapper=new LambdaQueryWrapper();
        receiverWrapper.eq(YxSessionTalkEntity::getSenderId,receiverId);
        receiverWrapper.eq(YxSessionTalkEntity::getReceiverId,senderId);
        YxSessionTalkEntity receiverEntity = baseMapper.selectOne(receiverWrapper);
        if(null==receiverEntity){
            receiverEntity = new YxSessionTalkEntity();
            receiverEntity.setSessionId(dto.getSessionId());
            receiverEntity.setReceiverId(receiverId);
            receiverEntity.setReceiverName(receiverName);
            receiverEntity.setHeadUrl(receiverUrl);
            receiverEntity.setCreateTime(new Date());
            receiverEntity.setUpdateTime(new Date());
            receiverEntity.setStatus(1);
            receiverEntity.setSenderId(receiverId);
            receiverEntity.setSenderName(senderName);
            receiverEntity.setSenderType(dto.getReceiverType());
            receiverEntity.setReceiverType(dto.getSenderType());
            baseMapper.insert(receiverEntity);
        }else{
            if(1!=receiverEntity.getStatus()){
                //激活会话
                receiverEntity.setUpdateTime(new Date());
                receiverEntity.setStatus(1);
                baseMapper.updateById(receiverEntity);
            }
        }
        YxSessionTalkRecordEntity recordEntity = new YxSessionTalkRecordEntity();
        recordEntity.setSessionId(dto.getSessionId());
        recordEntity.setSenderId(receiverId);
        recordEntity.setSenderName(receiverName);
        recordEntity.setTalkInfo(JsonUtils.toJson(vo));
        recordEntity.setCreateTime(new Date());
        recordEntity.setUpdateTime(new Date());
        recordEntity.setTalkInfoType(1);
        sessionTalkRecordMapper.insert(recordEntity);
        //发送会话消息
        MqttNoticeVo mqttVo = new MqttNoticeVo();
        mqttVo.setType(4);
        //接收人ID
        mqttVo.setReceiverId(dto.getReceiverId());
        mqttVo.setSysTime(new Date());
        //内容
        mqttVo.setContent(JsonUtils.toJson(vo));
        log.info("推送会话ID=============================================>{}",dto.getSessionId());
        log.info("推送会话内容=============================================>{}",dto.getContent());
        mqttGateway.sendToMqtt(MqttTopicEnum.TALK_SESSION_TOPIC.getTopic()+dto.getReceiverId(),JsonUtils.toJson(mqttVo));
    }

    /**
     * 创建会话
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createSessionTalk(CreateSessionTalkDto dto) {
        Integer receiverType = dto.getReceiverType();
        Integer senderType = dto.getSenderType();
        if((1 != receiverType && 2 != receiverType) || (1 != senderType && 2 != senderType)){
            throw new BaseException("发送者/接收者类型有误");
        }
        //查询接收者信息
        Long receiverId=dto.getReceiverId();
        String receiverName="";
        String receiverUrl="";
        if(1==receiverType){
            YxSysUserEntity userEntity = userMapper.selectById(receiverId);
            if(null==userEntity){
                throw new BaseException("未查询到接收人员信息");
            }
            receiverName=userEntity.getNickName();
            receiverUrl=userEntity.getHeadUrl();
        }else{
            YxLiveShopEntity shopEntity = shopMapper.selectById(receiverId);
            if(null==shopEntity){
                throw new BaseException("未查询到接收店铺信息");
            }
            receiverName=shopEntity.getShopName();
            receiverUrl=shopEntity.getShopAvatar();
        }
        //发送者
        Long senderId =dto.getSenderId();
        String senderName ="";
        if(1==senderType){
            YxSysUserEntity sendUserEntity = userMapper.selectById(senderId);
            if(null==sendUserEntity){
                throw new BaseException("未查询到发送者信息");
            }
            senderName=sendUserEntity.getNickName();
        }else{
            YxLiveShopEntity shopEntity = shopMapper.selectById(senderId);
            if(null==shopEntity){
                throw new BaseException("未查询到发送者信息");
            }
            senderName=shopEntity.getShopName();
        }
        //查询发送者与接受者的会话是否已经存在,这里涉及到session一致性问题
        String sessionId="";
        //查询发送者会话
        LambdaQueryWrapper<YxSessionTalkEntity> senderWrapper=new LambdaQueryWrapper();
        senderWrapper.eq(YxSessionTalkEntity::getSenderId,senderId);
        senderWrapper.eq(YxSessionTalkEntity::getReceiverId,receiverId);
        YxSessionTalkEntity senderTalkEntity = baseMapper.selectOne(senderWrapper);
        if(null!=senderTalkEntity){
            sessionId=senderTalkEntity.getSessionId();
        }else{
            //查询接收者会话
            LambdaQueryWrapper<YxSessionTalkEntity> receiverWapper=new LambdaQueryWrapper();
            receiverWapper.eq(YxSessionTalkEntity::getSenderId,receiverId);
            receiverWapper.eq(YxSessionTalkEntity::getReceiverId,senderId);
            YxSessionTalkEntity receiverTalkEntity = baseMapper.selectOne(senderWrapper);
            if(null!=receiverTalkEntity){
                sessionId=receiverTalkEntity.getSessionId();
            }
        }
        if(null==senderTalkEntity){
            sessionId =StringUtils.isBlank(sessionId)?UUID.randomUUID().toString().replaceAll("-", ""):sessionId;
            senderTalkEntity = new YxSessionTalkEntity();
            senderTalkEntity.setSessionId(sessionId);
            senderTalkEntity.setSenderId(senderId);
            senderTalkEntity.setSenderName(senderName);
            senderTalkEntity.setCreateTime(new Date());
            senderTalkEntity.setUpdateTime(new Date());
            senderTalkEntity.setStatus(1);
            senderTalkEntity.setReceiverId(receiverId);
            senderTalkEntity.setReceiverName(receiverName);
            senderTalkEntity.setHeadUrl(receiverUrl);
            senderTalkEntity.setSenderType(dto.getSenderType());
            senderTalkEntity.setReceiverType(dto.getReceiverType());
            baseMapper.insert(senderTalkEntity);
        }else{
            sessionId=senderTalkEntity.getSessionId();
            senderTalkEntity.setStatus(1);
            senderTalkEntity.setUpdateTime(new Date());
            baseMapper.updateById(senderTalkEntity);
        }
        return sessionId;
    }

    /**
     * 消息从未读变已读
     * @param sessionId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReadStatus(String sessionId) {
        LambdaQueryWrapper<YxSessionTalkEntity> talkWapper=new LambdaQueryWrapper();
        talkWapper.eq(YxSessionTalkEntity::getSessionId,sessionId);
        talkWapper.eq(YxSessionTalkEntity::getReceiverId,userUtil.getLoginUserId());
        YxSessionTalkEntity talkEntity = baseMapper.selectOne(talkWapper);
        if(null==talkEntity){
            throw new BaseException("查询会话失败");
        }
        LambdaUpdateWrapper<YxSessionTalkRecordEntity> updateWapper=new LambdaUpdateWrapper();
        updateWapper.set(YxSessionTalkRecordEntity::getReadStatus,1);
        updateWapper.eq(YxSessionTalkRecordEntity::getSenderId,talkEntity.getReceiverId());
        updateWapper.eq(YxSessionTalkRecordEntity::getSessionId,sessionId);
        sessionTalkRecordMapper.update(null,updateWapper);
    }

    //---------------------------------------------------------------------------------------------------------------------
    /**
     * 校验未关注的人员只能发送三条信息
     * sessionId::会话sessionID
     * receiverId:接收人
     * receiverType: 1:人员 2：店铺
     * senderType: 1:人员 2：店铺
     */
    private void validataFollow(String sessionId,Long receiverId,Integer receiverType,Long senderId,Integer senderType){
        //查询是否关注
        LambdaQueryWrapper<YxFollowEntity> followQueryWrapper=new LambdaQueryWrapper();
        followQueryWrapper.eq(YxFollowEntity::getFollowerId,receiverId);
        followQueryWrapper.eq(YxFollowEntity::getFolloweeId,senderId);
        //被关注者类型
        if(1==senderType){
            followQueryWrapper.eq(YxFollowEntity::getFolloweeType,1);
        }else{
            followQueryWrapper.eq(YxFollowEntity::getFolloweeType,0);
        }
        //关注者类型
        if(1==receiverType){
            followQueryWrapper.eq(YxFollowEntity::getFollowerType,1);
        }else{
            followQueryWrapper.eq(YxFollowEntity::getFollowerType,0);
        }
        followQueryWrapper.eq(YxFollowEntity::getFollowStatus,0);
        YxFollowEntity followEntity = followMapper.selectOne(followQueryWrapper);
        //未关注
        if(null==followEntity){
            //查询发送会话记录数量
            LambdaQueryWrapper<YxSessionTalkRecordEntity> sessioQueryWrapper=new LambdaQueryWrapper();
            sessioQueryWrapper.eq(YxSessionTalkRecordEntity::getSessionId,sessionId);
            sessioQueryWrapper.eq(YxSessionTalkRecordEntity::getSenderId,userUtil.getLoginUserId());
            Integer cnt = sessionTalkRecordMapper.selectCount(sessioQueryWrapper);
            if(cnt>=3){
                throw new BaseException("对方未回关您,私信消息最多能发送三条");
            }
        }
    }

    /**
     *会话中的文件上传
     * @param dto
     * @param file
     * @param talkId
     */
    private TalkSeesionInfoVo uploadFile(ClientSendTalkDTO dto, MultipartFile file, String talkId) {
        if(null==file){
            throw new BaseException("发送文件格式时,文件不能为空");
        }
        FileClassifyEnum fileClassifyEnum=null;
        TalkSeesionInfoVo vo = new TalkSeesionInfoVo();
        //图片文件校验
        if(2==dto.getContentType()){
            vo.setTalkType(2);
            if (file.getSize() > fileImageMaxSize) {
                throw new BaseException(CommonErrorEnum.FILE_SIZE_OUT_OF_RANG_ERROR.getCode(),CommonErrorEnum.FILE_SIZE_OUT_OF_RANG_ERROR.getType(),"不能上传超过" + fileImageMaxSize / 1024.0 / 1024.0 + "M的图片");
            }
            fileClassifyEnum=FileClassifyEnum.SESSION_IMAGES_FILE;
        }else{
            vo.setTalkType(3);
            //视频语音文件校验
            if (file.getSize() > fileVideoMaxSize) {
                throw new BaseException(CommonErrorEnum.FILE_SIZE_OUT_OF_RANG_ERROR.getCode(),CommonErrorEnum.FILE_SIZE_OUT_OF_RANG_ERROR.getType(),"不能上传超过" + fileVideoMaxSize / 1024.0 / 1024.0 + "M的视频或语音");
            }
            fileClassifyEnum=FileClassifyEnum.SESSION_VIDEO_FILE;
        }
        //图片上传华为云
        try {
            //存储objectKey
            String objectKey = fileClassifyEnum.getPath() + UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(CommonConstant.POINT));
            //上传附件
            String filePath = huaWeiObsUtil.uploadFile(objectKey, file.getInputStream());
            vo.setFileUrl(filePath);
           log.info("文件上传路径====================================>{}",filePath);
//           //视频文件需要抽取封面并上传
//           if(3==dto.getContentType()){
//               //本地绝对路径
//               String localCoverUrl = VideoCoverUtils.interceptCover(filePath);
//               String coverKey = FileClassifyEnum.SESSION_IMAGES_FILE.getPath() + UUID.randomUUID().toString().replace("-", "") .concat(".jpg");
//               InputStream inputStream = new FileInputStream(new File(localCoverUrl));
//               String coverUrl = huaWeiObsUtil.uploadFile(coverKey, inputStream);
//               vo.setCoverUrl(coverUrl);
//           }
           return vo;
        }catch (Exception e){
            log.error("上传异常",e);
            throw new BaseException("上传异常："+e.getMessage());
        }
    }
}
